package com.bosssoft.hr.train.jsp.example.listener;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.HashSet;

/**
 * 监听在线用户的数量
 */
@Slf4j
@SuppressWarnings("unchecked")
public class UserListener implements HttpSessionListener{

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        //获取servletContext
        ServletContext application = session.getServletContext();
        //获取有关统计登录人数的session并用hashset存储(防止重复)
        HashSet<HttpSession> sessions = (HashSet) application.getAttribute("name");
        if (sessions==null){
            sessions = new HashSet<>();
        }

        sessions.add(session);

        //将其存放到servlet context 方便jsp使用
        application.setAttribute("count",sessions.size());

        log.info("session 网站在线人数为"+sessions.size());
    }
}
